const axios = require('../../utils/axios');
const app = getApp();

Page({
  data: {
    appLanguage: 1 - app.globalData.appLanguage,
    focusedInput: -1,
    edited: false,

    data: {},
    user: {}
  },

  onLoad(options) {
    const user = app.globalData.user;
    this.setData({ data: user, user });
  },

  onFocusInput(e) {
    const { index } = e.currentTarget.dataset;
    this.setData({ focusedInput: index });
  },
  onBlurInput(e) {
    this.setData({ focusedInput: -1 });
  },
  onInput(e) {
    const { type } = e.currentTarget.dataset;
    const name = 'data.' + type;
    this.setData({ 
      [name]: e.detail.value,
      edited: true
    });
  },
  onChooseAvatar(e) {
    console.log(e.detail.avatarUrl);
    this.setData({ 'data.uAvatar': e.detail.avatarUrl });
  },

  onShow() {
    const user = app.globalData.user;
    this.setData({ data: user, user, edited: false });
  },

  onCancelChange() {
    this.setData({ edited: false, data: this.data.user });
  },
  onConfirmChange() {
    const { data } = this.data;
    console.log(data);
    const body = {
      id: data.id,
      info: {
        contact: data.contact,
        uSign: data.uSign,
        region: data.region,
        regionId: data.regionId
      },
    };

    console.log(body);
    const header = app.globalData.header;
    axios.put('/user', body, header).then(res => {
      const { code, err } = res;
      console.log(res);
      if (code == 200) {
        wx.showToast({
          title: '修改成功',
          icon: 'success'
        });
        this.setData({ edited: false });
        app.login(() => this.onLoad());
      } else if (code == 400) {
        app.login(() => this.onConfirmChange());
      } else throw err;
    }).catch(err => {
      wx.showModal({
        title: '错误',
        content: JSON.stringify(err),
        showCancel: false
      });
    });
  }
})